package com.asuka.task;

import com.alibaba.druid.sql.visitor.functions.If;
import com.asuka.entity.Orders;
import com.asuka.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {


    @Autowired
    private OrderMapper orderMapper;


    @Scheduled(cron = "0 0/7 * * * ?")
    public void orderCancel(){
        LocalDateTime now = LocalDateTime.now().plusMinutes(-15);

        Integer status = Orders.PENDING_PAYMENT;
        List<Orders> list = orderMapper.selectCancel(status,now);


        if(list != null && !list.isEmpty()){
            for (Orders order : list) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("订单超时，自动取消");
                orderMapper.updateById(order);
            }
        }

    }



    @Scheduled(cron = "0 0 0/2 * * ?")
    public void orderDelivery(){
        LocalDateTime now = LocalDateTime.now().plusHours(-2);


        Integer status = Orders.DELIVERY_IN_PROGRESS;
        List<Orders> list = orderMapper.selectCancel(status,now);


        if(list != null && !list.isEmpty()){
            for (Orders order : list) {
                order.setStatus(Orders.COMPLETED);
                orderMapper.updateById(order);
            }
        }

    }

}
